package middlewares

import (
	"encoding/json"
	"io/ioutil"
	"net/http"
	"strings"

	"github.com/spf13/cast"
)

/**
 * 解析JSON、XML等参数中间件，且将参数添加到PostForm
 *
 * @param http.HandlerFunc next ------------------------------必传
 * @return http.HandlerFunc
 * @author huwl
 */
func ParseArgsMiddleware(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		contentType := r.Header.Get("Content-Type")
		if strings.Contains(contentType, "application/json") {
			var params map[string]interface{}
			body, _ := ioutil.ReadAll(r.Body)
			json.Unmarshal(body, &params)
			r.ParseForm()
			for k, v := range params {
				switch v.(type) {
				case string, float64, int, int64:
					r.PostForm.Add(k, cast.ToString(v))
					r.Form.Add(k, cast.ToString(v))
				case []interface{}:
					for _, val := range v.([]interface{}) {
						r.PostForm.Add(k, cast.ToString(val))
						r.Form.Add(k, cast.ToString(val))
					}
				}
			}
		}

		next(w, r)
	}
}
